﻿using Chire.ChireInter.Class;
using Chire.ChireInter.Students;
using Chire.wechat;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Web;

namespace Chire.ChireInter.Event_calendar
{
       public enum EventType
        {
           EventTypeClass = 1,              /**< 课表事件*/
           EventTypeOther = 0,              /**< 其他事件*/
        }

    public class Event_Action
    {
        #region 添加事件
        public string addEventManager(string name,string time ,string classId,EventType type){
            // 1.获取日期

            DateTime interfaceDateTime =  Convert.ToDateTime(time);
          
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            TimeSpan ts = (interfaceDateTime - startTime);

            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string StrInsert = "";
            StrInsert = "insert into event_calendar(id,title,date,time,dateInterval,timeInterval,has_del,class_id,hasPush,type) values(@id,@title,@date,@time,@dateInterval,@timeInterval,@has_del,@class_id,@hasPush,@type)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值
            // 1. 事件id
            string eventId = Constance.Instance.getRandomStr(30);
            cmd.Parameters.Add("@id", SqlDbType.VarChar, 50);
            cmd.Parameters["@id"].Value = eventId;
            // 1. 标题
            cmd.Parameters.Add("@title", SqlDbType.VarChar, 100);
            cmd.Parameters["@title"].Value = name;
            // 2.日期
            cmd.Parameters.Add("@date", SqlDbType.VarChar, 1000);
            cmd.Parameters["@date"].Value = interfaceDateTime.Date.ToShortDateString();

            // 3.时间
            cmd.Parameters.Add("@time", SqlDbType.VarChar, 1000);
            cmd.Parameters["@time"].Value = interfaceDateTime.ToLongTimeString().ToString(); 
            // 4.日期时间戳
            cmd.Parameters.Add("@dateInterval", SqlDbType.VarChar, 1000);
            cmd.Parameters["@dateInterval"].Value = ts.TotalSeconds;
            // 5.时间时间戳
            cmd.Parameters.Add("@timeInterval", SqlDbType.VarChar, 1000);
            cmd.Parameters["@timeInterval"].Value = ts.TotalSeconds;
            // 6. 是否删除
            cmd.Parameters.Add("@has_del", SqlDbType.Int, 10);
            cmd.Parameters["@has_del"].Value = 0;
            // 7.课程编号
            cmd.Parameters.Add("@class_id", SqlDbType.VarChar, 30);
            cmd.Parameters["@class_id"].Value = classId;

            cmd.Parameters.Add("@hasPush", SqlDbType.Int);
            cmd.Parameters["@hasPush"].Value = 0;

            cmd.Parameters.Add("@type", SqlDbType.Int);
            cmd.Parameters["@type"].Value = (int)type;
            
            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
            return eventId;
        }
        #endregion

        #region 获取某天事件列表
        public List<Event_Model> getEventList(string date)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "";
            if (date.Length > 0)
            {
                strselect = "select * from event_calendar  where [date] = '" + date + "' order by id desc";

            }
            else {
                strselect = "select * from event_calendar";
            }
            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Event_Model> eventList = new List<Event_Model>();
            Class_Action classAction = new Class_Action();
            for (int i = 0; i < rows; i++)
            {
                string id = dt.Rows[i]["id"].ToString();
                string title = dt.Rows[i]["title"].ToString();
                string dates = dt.Rows[i]["date"].ToString();
                string time = dt.Rows[i]["time"].ToString();
                long dateInterval = (long)Convert.ToInt64(dt.Rows[i]["dateInterval"].ToString());
                long timeInterval = (long)Convert.ToInt64(dt.Rows[i]["timeInterval"].ToString());
                int has_del = Convert.ToInt32(dt.Rows[i]["has_del"].ToString());
                string class_id = dt.Rows[i]["class_id"].ToString();
                Class_Model classModel = classAction.getClassInfoWithId(class_id);
                Event_Model eventModel = new Event_Model() {classModel =classModel,  id = id, title = title, date = dates, time = time, dateInterval = dateInterval, timeInterval = timeInterval, has_del = has_del, class_id = class_id };
                eventList.Add(eventModel);
            }
            sqlcon.Close();
            return eventList;
        }
        #endregion

        #region 获取月分列表
        public List<Event_Month_Model> eventMoonList(string year, string moon)
        {
            
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select [date],count(*) from event_calendar where DATEPART(m,[date]) = "+moon+" and DATEPART(yy,[date]) = "+year+" GROUP BY [date]";
            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Event_Month_Model> eventList = new List<Event_Month_Model>();
            for (int i = 0; i < rows; i++)
            {
                string date = dt.Rows[i]["date"].ToString();
                int count = Convert.ToInt32(dt.Rows[i][1].ToString());

                Event_Month_Model eventModel = new Event_Month_Model() {date = date,count = count };
                eventList.Add(eventModel);
            }
            sqlcon.Close();
            return eventList;
        }
        #endregion

        #region 获取微信课表列表
        public List<Event_Wechat_Model> getWechatEventList()
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from event_calendar";
    
            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Event_Wechat_Model> eventList = new List<Event_Wechat_Model>();
            for (int i = 0; i < rows; i++)
            {
                string title = dt.Rows[i]["title"].ToString();
                string dates = dt.Rows[i]["date"].ToString();
                string time = dt.Rows[i]["time"].ToString();
               

                // time 转换成date
                DateTime dateTime = Convert.ToDateTime(dates);
                DateTime timeDateTime = Convert.ToDateTime(time);
                string nTitle = timeDateTime.Hour.ToString() + ":" + timeDateTime.Minute.ToString() + "  " + title;
                

                string nTimeStr = dateTime.Day.ToString() + "-" + dateTime.Month.ToString() + "-" + dateTime.Year.ToString();
                Event_Wechat_Model eventModel = new Event_Wechat_Model() { title = nTitle, time = time, date = nTimeStr };
                eventList.Add(eventModel);
            }
            sqlcon.Close();
            return eventList;
        }

        #endregion

        #region 对学生插入事件
        public void addEventWithStudent(string userId, string eventId) {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string StrInsert = "";
            StrInsert = "insert into event_calendar_user(event_id,userId) values(@event_id,@userId)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值
   
            cmd.Parameters.Add("@event_id", SqlDbType.VarChar, 50);
            cmd.Parameters["@event_id"].Value = eventId;
            // 1. 标题
            cmd.Parameters.Add("@userId", SqlDbType.VarChar, 100);
            cmd.Parameters["@userId"].Value = userId;
          

            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }
        #endregion

        #region 获取当前学生的事件Id列表
        public List<string> getEventListWithUserId(string userId) {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from event_calendar_user  where userId = '"+ userId+"'";

            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<string> eventList = new List<string>();
            for (int i = 0; i < rows; i++)
            {
                string event_id = dt.Rows[i]["event_id"].ToString();
                eventList.Add(event_id);
            }
            sqlcon.Close();
            return eventList;
        }
        #endregion

        #region 根据事件Id 获取当前的事件
        public Event_Model getEventWithEventId(string eventId)
        {

            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select* from event_calendar where id = '" + eventId + "'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            Event_Model info = new Event_Model();
            if (dr.Read())
            {
   
                info.id = dr["id"].ToString();
                info.title = dr["title"].ToString();
                info.date = dr["date"].ToString();
                info.time = dr["time"].ToString();
                info.dateInterval =(long)Convert.ToInt64( dr["dateInterval"].ToString());
                info.timeInterval =(long)Convert.ToInt64( dr["timeInterval"].ToString());
                info.has_del = Convert.ToInt32(dr["has_del"].ToString());
                info.class_id = dr["class_id"].ToString();

            }
            sqlcon.Close();
            return info;
        
        }
        #endregion

        #region 删除事件
        public void eventDeleteWithEventId(string eventId)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strSqls = "update event_calendar set has_del = 1 where id = '" + eventId + "'";
            SqlCommand cmd = new SqlCommand(strSqls, sqlcon);
            //添加参数并且设置参数值
            cmd.ExecuteNonQuery();
            sqlcon.Close();
           
        }

        #endregion

        #region 删除事件下面所有的内容
        public void eventDeleteWithAllEvent(string eventId)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "delete from event_calendar_user where event_id = '" + eventId + "'";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值

            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }
        #endregion

        #region 删除事件下面所有的内容
        public void eventDeleteEventWithUserAndEventId(string eventId ,string userId)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "delete from event_calendar_user where event_id = '" + eventId + "' and userId = '" + userId + "'";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值

            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }
        #endregion

        #region 获取事件对应的所有学生
        public List<Event_Student> getEventStudentList(string eventId)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from event_calendar_user  where event_id = '" + eventId + "'";

            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Event_Student> eventList = new List<Event_Student>();
            Student_Action studentAction = new Student_Action();
            for (int i = 0; i < rows; i++)
            {
                string id = dt.Rows[i]["id"].ToString();
                string event_id = dt.Rows[i]["event_id"].ToString();
                string userId = dt.Rows[i]["userId"].ToString();
                Student_Model studentModel = studentAction.getStudentInfoWithId(userId);
                Event_Student eventModel = new Event_Student() {student = studentModel, id = id, event_id = event_id, userId = userId};
                eventList.Add(eventModel);
            }
            sqlcon.Close();
            return eventList;
        }
        #endregion

        #region 获取微信未被推送的事件列表
        public List<Event_Model> getEventListWithNotPush()
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from event_calendar where hasPush != 1 and type = "+(long)EventType.EventTypeOther+"";
            
            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Event_Model> eventList = new List<Event_Model>();
            Class_Action classAction = new Class_Action();
            for (int i = 0; i < rows; i++)
            {
                string id = dt.Rows[i]["id"].ToString();
                string title = dt.Rows[i]["title"].ToString();
                string dates = dt.Rows[i]["date"].ToString();
                string time = dt.Rows[i]["time"].ToString();
                long dateInterval = (long)Convert.ToInt64(dt.Rows[i]["dateInterval"].ToString());
                long timeInterval = (long)Convert.ToInt64(dt.Rows[i]["timeInterval"].ToString());
                int has_del = Convert.ToInt32( dt.Rows[i]["has_del"].ToString());
                string class_id = dt.Rows[i]["class_id"].ToString();
                Class_Model classModel = classAction.getClassInfoWithId(class_id);
                Event_Model eventModel = new Event_Model() {classModel = classModel, id = id, title = title, date = dates, time = time, dateInterval = dateInterval, timeInterval = timeInterval, has_del = has_del, class_id = class_id };
                eventList.Add(eventModel);
            }
            sqlcon.Close();
            return eventList;
        }
        #endregion

        #region 设置微信已推送学生标记
        public void wechatSettingSignPush(string eventId) {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strSqls = "update event_calendar set hasPush = 1 where id = '" + eventId + "'";
            SqlCommand cmd = new SqlCommand(strSqls, sqlcon);
            //添加参数并且设置参数值
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }
        #endregion

        #region 微信每日晚统计发送课表信息
        public void WechatPushEventManager(string openId, string name,string className,string date) {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = name;
            first.color = "#6595A4";

            WechatModelData classNameModel = new WechatModelData();
            classNameModel.value = className;
            classNameModel.color = "#6595A4";

            WechatModelData dateModel = new WechatModelData();
            dateModel.value = date;
            dateModel.color = "#6595A4";

            WechatModelData remark = new WechatModelData();
            remark.value = "如有请假请家长与课程老师进行联系。谢谢。";
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.userName = first;
            list.courseName = classNameModel;
            list.date = dateModel;
            list.remark = remark;

            wechatToken.wechatPushClassEvent(openId, list);
        }
        #endregion

        #region 进行插入每周的上课记录
        public void eventWeekAdd(long beginTime, long endTime) {
            // 1. 获取开始时间
            DateTime begin = Constance.ConvertLongToDateTime(beginTime);
            string beginStr = begin.ToShortDateString();
            DateTime beginDay = Convert.ToDateTime(beginStr);
            long beginDayInt = Constance.Instance.ConvertDateTimeInt(beginDay);

            // 1. 获取结束时间
            DateTime end = Constance.ConvertLongToDateTime(endTime);
            string endStr = end.ToShortDateString();
            DateTime endDay = Convert.ToDateTime(endStr);
            long endDayInt = Constance.Instance.ConvertDateTimeInt(endDay);


            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string StrInsert = "";
            StrInsert = "insert into event_auto_insert(id,beginWeekTime,endWeekTime,datetime) values(@id,@beginWeekTime,@endWeekTime,@datetime)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值

            cmd.Parameters.Add("@id", SqlDbType.VarChar, 50);
            cmd.Parameters["@id"].Value = Constance.Instance.getRandomStr(20);
            // 1. 标题
            cmd.Parameters.Add("@beginWeekTime", SqlDbType.Int);
            cmd.Parameters["@beginWeekTime"].Value = beginDayInt;

            cmd.Parameters.Add("@endWeekTime", SqlDbType.Int);
            cmd.Parameters["@endWeekTime"].Value = endDayInt;

            cmd.Parameters.Add("@datetime", SqlDbType.VarChar,40);
            cmd.Parameters["@datetime"].Value = DateTime.Now.ToString();
            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }

        public bool eventWeekHas(long beginTime, long endTime) {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from event_auto_insert where beginWeekTime > " + beginTime + " or beginWeekTime = " + beginTime + "";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            bool has = false;
            if (dr.Read())
            {
               
                
                    has = true;
              
            }
            sqlcon.Close();
            return has;
        }
        #endregion

        #region 3.获取今天星期几
        public string getCurrentDay(DateTime time)
        {
            string[] Day = new string[] { "0", "1", "2", "3", "4", "5", "6" };
            string week = Day[Convert.ToInt32(time.DayOfWeek.ToString("d"))].ToString();
            return week;
        }

      
        #endregion

        #region 对今天已经推送的内容设置已腿送
        public void eventTodaySettingHasPush() { 
            
        }
        #endregion
    }
}